package com.stony.orc;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

/**
 * <p>orcTest
 * <p>com.stony.orc
 *
 * @author stony
 * @version 下午4:03
 * @since 2017/11/16
 */
public class HttpService implements AutoCloseable,API {

    private static final Logger logger = LoggerFactory.getLogger(HttpService.class);
    public final OkHttpClient client;

    public HttpService() {
        client = new OkHttpClient.Builder()
                .addInterceptor(new LoggingInterceptor())
                .connectionPool(new ConnectionPool(10, 5, TimeUnit.MINUTES))
                .connectTimeout(2000, TimeUnit.MILLISECONDS)
                .readTimeout(2000, TimeUnit.MILLISECONDS)
                .writeTimeout(1800, TimeUnit.MILLISECONDS)
                .build();
    }

    public String execute(Request request) throws IOException {
        Response response = client.newCall(request).execute();
        String body = null;
        if(response.isSuccessful()) {
            body = response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
        response.close();
        return body;
    }

    public <T> T get(String url, Map<String, String> map, Class<T> type) throws IOException {
        return JsonUtils.str2Obj(get(url, map), type);
    }
    public String get(String url, Map<String, String> map) throws IOException {
        Request request = new Request.Builder()
                .get()
                .url(buildUrl(url, map))
                .build();
        return execute(request);
    }

    public <T> T submit(String url, Map<String, String> map, Class<T> type) throws IOException {
        return JsonUtils.str2Obj(submit(url, map), type);
    }
    public String submit(String url, Map<String, String> map) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        map.forEach(builder::add);
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        return execute(request);
    }
    public String submit(String url, String key, String value) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        builder.add(key, value);
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        return execute(request);
    }

    public String submit(String url, Collection<SubmitBody> bodies) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for (SubmitBody body : bodies) {
            builder.add(body.key, body.value);
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        return execute(request);
    }
    public static SubmitBody makeSubmitBody(String key, String value) {
        return new SubmitBody(key, value);
    }
    private static class SubmitBody {
        String key;
        String value;
        SubmitBody(String key, String value) {
            this.key = key;
            this.value = value;
        }
    }
    public String buildUrl(String url, Map<String, ?> params){
        if(params == null || params.isEmpty()){
            return url;
        }
        StringBuilder _url = new StringBuilder(url);
        StringBuilder _params = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String,?> entry : params.entrySet()){
            if(first){
                _params.append(entry.getKey()).append("=").append(entry.getValue());
                first = false;
            } else{
                _params.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
        }
        if(url.contains("?")){
            _url.append("&").append(_params.toString());
        }else{
            _url.append("?").append(_params.toString());
        }
        return _url.toString();
    }

    @Override
    public void close() throws Exception {
        if(client != null) {
            client.dispatcher().executorService().shutdown();   //清除并关闭线程池
            client.connectionPool().evictAll();                 //清除并关闭连接池
            client.cache().close();                             //清除cache
        }
    }
    class LoggingInterceptor implements Interceptor {
        @Override public Response intercept(Interceptor.Chain chain) throws IOException {
            Request request = chain.request();

            long t1 = System.nanoTime();
            logger.info(String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));

            Response response = chain.proceed(request);

            long t2 = System.nanoTime();
            logger.info(String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));

            return response;
        }
    }

    void handler(Runnable runnable) {
        executorService.submit(runnable);
    }
}
